using UnityEngine;

[RequireComponent(typeof(BoxCollider2D))]
[RequireComponent(typeof(Rigidbody2D))]
public class MoveItem : MonoBehaviour
{
    #region SOUND EFFECT
    [Header("音效")]
    #endregion SOUND EFFECT
    #region Tooltip
    [Tooltip("移动此项目时的声音效果")]
    #endregion Tooltip
    [SerializeField] private SoundEffectSO moveSoundEffect;

    [HideInInspector] public BoxCollider2D boxCollider2D;
    private Rigidbody2D rigidBody2D;
    private InstantiatedRoom instantiatedRoom;
    private Vector3 previousPosition;

    private void Awake()
    {
        // 获取组件引用
        boxCollider2D = GetComponent<BoxCollider2D>();
        rigidBody2D = GetComponent<Rigidbody2D>();
        instantiatedRoom = GetComponentInParent<InstantiatedRoom>();

        // 将此项目添加到项目障碍数组中
        instantiatedRoom.moveableItemsList.Add(this);
    }

    /// <summary>
    /// 当有东西接触时更新障碍物位置
    /// </summary>
    private void OnCollisionStay2D(Collision2D collision)
    {
        UpdateObstacles();
    }


    /// <summary>
    /// 更新障碍物位置
    /// </summary>
    private void UpdateObstacles()
    {
        // 确保物品留在房间内
        ConfineItemToRoomBounds();

        // 更新障碍物数组中的可移动物品
        instantiatedRoom.UpdateMoveableObstacles();

        // 在碰撞后捕获新位置
        previousPosition = transform.position;

        // 如果移动，则播放声音（允许小速度）
        if (Mathf.Abs(rigidBody2D.velocity.x) > 0.001f || Mathf.Abs(rigidBody2D.velocity.y) > 0.001f)
        {
            // 每 10 帧播放一次移动声音
            if (moveSoundEffect != null && Time.frameCount % 10 == 0)
            {
                SoundEffectManager.Instance.PlaySoundEffect(moveSoundEffect);
            }
        }
    }

    /// <summary>
    /// 将物品限制在房间范围内
    /// </summary>
    private void ConfineItemToRoomBounds()
    {
        Bounds itemBounds = boxCollider2D.bounds;
        Bounds roomBounds = instantiatedRoom.roomColliderBounds;

        // 如果项目被推到房间边界之外，则将项目位置设置为其
        // previous position
        if (itemBounds.min.x <= roomBounds.min.x ||
            itemBounds.max.x >= roomBounds.max.x ||
            itemBounds.min.y <= roomBounds.min.y ||
            itemBounds.max.y >= roomBounds.max.y)
        {
            transform.position = previousPosition;
        }

    }

}